package cn.jx.asc.controller;

import cn.jx.asc.common.constant.Contants;
import cn.jx.asc.common.constant.JwtConst;
import cn.jx.asc.common.enums.ResultStatus;
import cn.jx.asc.common.enums.UserStatu;
import cn.jx.asc.common.jwt.JwtToken;
import cn.jx.asc.common.response.Result;
import cn.jx.asc.common.response.ResultUtils;
import cn.jx.asc.common.utils.JwtUtils;
import cn.jx.asc.common.utils.MD5Utils;
import cn.jx.asc.pojo.bo.LoginUserBO;
import cn.jx.asc.pojo.bo.RegistUserBO;
import cn.jx.asc.pojo.entity.User;
import cn.jx.asc.service.RoleService;
import cn.jx.asc.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


/**
 * 登入授权
 *
 * @author lhg
 */

@Api(value = "注册登入",tags ={"用于注册登入的相关接口"} )
@RestController
@RequestMapping("/passport")
@Slf4j
public class PortpassController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    @ApiOperation(value = "用户名是否存在",notes = "用户名是否存在",httpMethod = "GET")
    @GetMapping("/usernameIsExist")
    public Result usernameIsExist(
            @ApiParam(name = "username",value = "用户名",required = true)
            @RequestParam String username){
        //判断用户名是否存在
        if (StringUtils.isBlank(username)){
            return ResultUtils.resultWithoutData(ResultStatus.NOT_USERNAME);
        }
        boolean usernameIsExist = userService.queryUsernameIsExist(username);
        if (usernameIsExist){
            return ResultUtils.resultWithoutData(ResultStatus.USERNAME_EXISTS);
        }
        return ResultUtils.resultWithoutData(ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "职工号",notes = "职工号是否存在",httpMethod = "GET")
    @GetMapping("/userIdIsExist")
    public Result userIdIsExist(
            @ApiParam(name = "userId",value = "用户id",required = true)
            @RequestParam String userId){
        //判断职工号是否存在
        if (StringUtils.isBlank(userId)){
            return ResultUtils.resultWithoutData(ResultStatus.NOT_EMPLOYEE_NUMBER);
        }
        boolean userIdIsExist = userService.queryUserIdIsExist(userId);
        if (userIdIsExist){
            return ResultUtils.resultWithoutData(ResultStatus.EMPLOYEE_NUMBER_EXISTS);
        }


        return ResultUtils.resultWithoutData(ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "用户注册",notes = "用户注册",httpMethod = "POST")
    @PostMapping("/regist")
    public Result regist(
            @ApiParam(name = "registUserBO",value = "注册用户对象",required = true)
            @RequestBody RegistUserBO registUserBO){
        String userId = registUserBO.getUserId();
        String username = registUserBO.getUsername();
        String realname = registUserBO.getRealname();
        String password = registUserBO.getPassword();
        String confirmPwd = registUserBO.getConfirmPassword();

        if (StringUtils.isBlank(userId)){
            return ResultUtils.resultWithoutData(ResultStatus.NOT_EMPLOYEE_NUMBER);
        }
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(confirmPwd) ){
            return ResultUtils.resultWithoutData(ResultStatus.NOT_USERNAME_PASSWORD);
        }
        if (StringUtils.isBlank(realname)){
            return ResultUtils.resultWithoutData(ResultStatus.REAL_NAME_IS_EMPTY);
        }
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist){
            return ResultUtils.resultWithoutData(ResultStatus.USERNAME_EXISTS);
        }
        if (password.length()< Contants.MIN_PASSWORD_LENGTH){
            return ResultUtils.resultWithoutData(ResultStatus.PASSWORD_LENGTH_IS_WRONG);
        }
        if (!password.equals(confirmPwd)){
           return ResultUtils.resultWithoutData(ResultStatus.INCONSISTENT_PASSWORDS);
        }
       userService.createUser(registUserBO);
        return ResultUtils.resultWithoutData(ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "用户登入",notes = "用户登入",httpMethod = "POST")
    @PostMapping("/login")
    public Result login(@RequestBody LoginUserBO loginUserBO, HttpServletResponse response){
        String username = loginUserBO.getUsername();
        String password = loginUserBO.getPassword();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            return ResultUtils.resultWithoutData(ResultStatus.NOT_USERNAME_PASSWORD);
        }
        String pwd = null;
        try {
            pwd = MD5Utils.getMD5Str(password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        User userResult = null;
        try {
            userResult = userService.queryUserForLogin(username, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userResult == null ){
            return ResultUtils.resultWithoutData(ResultStatus.WRONG_USER_NAME_OR_PASSWORD);
        }

        if (userResult.getStatu().equals(UserStatu.REGISTER.type)){
            return ResultUtils.resultWithoutData(ResultStatus.USER_IS_NOT_ACTIVATED);
        }

        if (userResult.getStatu().equals(UserStatu.DEACTIVATE.type)){

            return ResultUtils.resultWithoutData(ResultStatus.USER_DISABLE);
        }
         String token = JwtUtils.sign(username, pwd);
        response.setHeader(JwtConst.RESPONSE_HEADER, token);
        response.setHeader("Access-control-Expose-Headers", JwtConst.RESPONSE_HEADER);

        Subject subject = SecurityUtils.getSubject();
        JwtToken jwtToken = new JwtToken(token);

        subject.login(jwtToken);

        return ResultUtils.resultWithoutData(ResultStatus.SUCCESS,
                "欢迎 " +loginUserBO.getUsername()+ " 进入稀土原地浸矿智能管控系统");
    }

    @ApiOperation(value = "用户退出登入",notes = "用户退出登入",httpMethod = "POST")
    @PostMapping("/logout")
    public Result logout( ){
        try{
            SecurityUtils.getSubject().logout();
            return ResultUtils.resultWithoutData(ResultStatus.SUCCESS);
        }catch (Exception e){
            log.error("异常抛出, subject.logout(): {}", e.getMessage());
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

    }

}
